//
//  SearchResultTopicViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/12/11.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "TopicListCell.h"
#import "LJMoreTopicCell.h"
#import "LJProfessionalAnswerCell.h"
#import "LJPopularQACell.h"
#import "LJSectionHeaderView.h"
#import "BA_CommunityInputTextView.h"

#import "TopicListViewController.h"
#import "TopicDetailViewController.h"
#import "QAPublishViewController.h"

#import "SearchResultTopicViewController.h"

@interface SearchResultTopicViewController ()<UITableViewDelegate, UITableViewDataSource, BA_BottomInputViewDelegate, UITextViewDelegate>

@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, assign) NSInteger selectIndex;

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) NSMutableArray <CommonPostModel*>* dataArray;

@property (nonatomic, strong) BA_CommunityInputTextView *footView;
@end

@implementation SearchResultTopicViewController

- (instancetype)initWithKeyWord:(NSString *)keyWord {
    
    self = [super init];
    
    if (self) {
        self.keyWord = keyWord;
    }
    return self;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchCallBack:) name:@"searchNoti" object:nil];

    UIWindow * keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:self.footView];
    [self.footView hideView];
    
    [self initView];
    [self refreshParam];
    [self request_data];
}

- (void)refreshParam {
    self.pageSize = 10;
    self.pageNum = 1;
}

- (void)initView {
    
    [self.view addSubview:self.tableview];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
}

-(void)searchCallBack:(NSNotification *)Noti {
    
    self.keyWord = [Noti.userInfo objectForKey:@"keyWord"];
    [self refreshParam];
    [self request_data];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:NO];
    [[IQKeyboardManager sharedManager] setEnable:NO];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:YES];
    [[IQKeyboardManager sharedManager] setEnable:YES];

    [self.footView hideView];
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    
    [self.footView hideView];
}

-(BOOL)textViewShouldEndEditing:(UITextView *)textView {
    
    [self.footView hideView];
    return YES;
}

-(void)BA_BottomInputViewSendTextMessage:(NSString *)message {
    
    [self request_postEvaWithIndex:self.selectIndex AndContent:message];
}

- (void)request_data {
    
    [SVProgressHUD showWithStatus:@"正在请求数据"];
      [self request_postList];

}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataArray.count;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return [TopicListCell calculateHeight];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {

    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    return [UIView new];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    TopicListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TopicListCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    
    [cell fillWithModel:self.dataArray[indexPath.row]];
    
    WEAKSELF
    cell.TopicListSectionHeaderBlock = ^(CommunityActionType type) {
      
        switch (type) {
            case CommunityActionType_Eva:{
                
                weakSelf.selectIndex = indexPath.row;
                [weakSelf.footView showView];
                [weakSelf.footView.textView becomeFirstResponder];
                
            } break;
            case CommunityActionType_Thumb:{
                
                weakSelf.selectIndex = indexPath.row;
                [weakSelf request_postThumbWithIndex:indexPath.row];
                
            } break;
                
            default:
                break;
        }
        
    };
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TopicDetailViewController *vc = [[TopicDetailViewController alloc] init];
    vc.pid = self.dataArray[indexPath.row].pid;
    [self.navigationController pushViewController:vc animated:YES];
}

- (BA_CommunityInputTextView *)footView {
    if (_footView == nil) {
        _footView = [[BA_CommunityInputTextView alloc]init];
        _footView.delegate = self;
        _footView.textView.delegate = self;
    }
    return _footView;
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xf1f1f1);
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"TopicListCell" bundle:nil] forCellReuseIdentifier:@"TopicListCellID"];
        [_tableview registerNib:[UINib nibWithNibName:@"LJMoreTopicCell" bundle:nil] forCellReuseIdentifier:@"LJMoreTopicCellID"];
        [_tableview registerNib:[UINib nibWithNibName:@"LJProfessionalAnswerCell" bundle:nil] forCellReuseIdentifier:@"LJProfessionalAnswerCellID"];
        [_tableview registerNib:[UINib nibWithNibName:@"LJPopularQACell" bundle:nil] forCellReuseIdentifier:@"LJPopularQACellID"];
        
        WEAKSELF
        _tableview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [weakSelf refreshParam];
            [weakSelf request_data];
        }];
        
        _tableview.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            weakSelf.pageNum ++;
            [weakSelf request_data];
        }];
        _tableview.mj_footer.ignoredScrollViewContentInsetBottom = Is_IPhoneX ? Bottom_SafeHeight : CGFLOAT_MIN;

    }
    return _tableview;
}


- (void)request_postList {
        
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    NSDictionary *t = @{}.mutableCopy;

    //综合排序 1：综合 2：价格由高到低 3：价格由低到高  4热门
    [t setValue:self.keyWord forKey:@"searchName"];
    [t setValue:@"6" forKey:@"type"];
    [t setValue:[TTUserModel sharedObject].cityId forKey:@"sellerCityId"];
    [t setValue:[TTUserModel sharedObject].userId forKey:@"replyUserId"];

    [dic setValue:t forKey:@"t"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_SearchAll];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    
                    NSArray *list = [resultDic valueForKey:@"list"];
                    
                    if ([list isKindOfClass:[NSArray class]]) {
                        
                        if (weakSelf.pageNum == 1) {
                            weakSelf.dataArray = @[].mutableCopy;
                            
                            if (list.count == 0) {
                                
                                [[TTNoResultManager shareManager] showNoResultWithStateInView:weakSelf.tableview errorCode:kTTViewState_GoAsk btnTitle:@"去提问" didPressButton:^{
                                    
                                    QAPublishViewController *vc = [[QAPublishViewController alloc] init];
                                    [weakSelf.navigationController pushViewController:vc animated:YES];
                                }];
                                
                            }
                        }
                            
                        for (NSDictionary *dic in list) {
                            CommonPostModel *model = [CommonPostModel modelWithDictionary:dic];
                            
                            model.textHeight = [Utilities getStringHeightWithText:model.content font:[UIFont systemFontOfSize:14] viewWidth:(TTScreenWidth - 28)];
                            
                            if (model.sysMediaList.count > 0) {
                                model.imageHeight = (TTScreenWidth - 32)/3 + 10;
                            } else {
                                model.imageHeight = CGFLOAT_MIN;
                            }
                            
                            NSArray *sysMediaList = [dic valueForKey:@"sysMediaList"];
                            if ([sysMediaList isKindOfClass:[NSArray class]]) {
                                model.sysMediaList = @[].mutableCopy;
                                model.photoArray = @[].mutableCopy;
                                for (id mediaDic in sysMediaList) {
                                    
                                    CommonMediaModel *mediaModel = [[CommonMediaModel alloc] init];
                                    if ([mediaDic isKindOfClass:[NSDictionary class]]) {
                                        NSDictionary *media = mediaDic;
                                        mediaModel = [CommonMediaModel modelWithDictionary:media];
                                        [model.photoArray addObject:mediaModel.url];

                                    }
                                    
                                    if ([mediaDic isKindOfClass:[NSString class]]) {
                                        NSString *media = mediaDic;
                                        mediaModel.url = media;
                                        [model.photoArray addObject:media];
                                    }
                                    
                                    [model.sysMediaList addObject:mediaModel];
                                }
                            }
                            
                            NSArray *sysPostChildList = [dic valueForKey:@"sysPostChildList"];
                            if ([sysPostChildList isKindOfClass:[NSArray class]]) {
                                model.sysPostChildList = @[].mutableCopy;
                                for (NSDictionary * evaDic in sysPostChildList) {
                                    CommunityEvaModel *evaModel = [CommunityEvaModel modelWithDictionary:evaDic];
                                    [model.sysPostChildList addObject:evaModel];
                                }
                            }
                            
                            [weakSelf.dataArray addObject:model];
                        }
                            
                    } else {
                        
                    }
                    [weakSelf.tableview reloadData];
                }
            }
        }

    } FailedBlock:^(NSError * _Nonnull error) {

        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
    }];
}

- (void)request_postEvaWithIndex:(NSInteger)index AndContent:(NSString *)content {
        
    CommonPostModel *model = self.dataArray[index];
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:content forKey:@"content"];

    [dic setValue:model.pid forKey:@"baseId"];
    [dic setValue:@"2" forKey:@"level"];
    [dic setValue:model.source forKey:@"source"];
    [dic setValue:model.userId forKey:@"userId"];
    
    //操作类型（1：评论，2：点赞，3：删除，4：下架，5：取消点赞）必传
    [dic setValue:@"1" forKey:@"mold"];

    //类型（1：谈婚，2：论嫁，3：问答）必传
    [dic setValue:@"1" forKey:@"type"];
    //层级（1,2,3）必传
    [dic setValue:@"2" forKey:@"replySource"];
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"replyUserId"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_CommonEva];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在发布评论"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                weakSelf.footView.textView.text = @"";
                [weakSelf.view endEditing:YES];
                
                [weakSelf request_data];
                
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}


- (void)request_postThumbWithIndex:(NSInteger)index {
        
    CommonPostModel *model = self.dataArray[index];

    NSMutableDictionary *dic = @{}.mutableCopy;

    //点赞帖子
    [dic setValue:model.pid forKey:@"baseId"];
    [dic setValue:@"1" forKey:@"level"];
    [dic setValue:model.source forKey:@"source"];
    [dic setValue:model.userId forKey:@"userId"];

    
    //操作类型（1：评论，2：点赞，3：删除，4：下架，5：取消点赞）必传
    if (model.isZan.length > 0) {
        [dic setValue:@"5" forKey:@"mold"];
        [dic setValue:model.isZan forKey:@"otherId"];
    } else {
        [dic setValue:@"2" forKey:@"mold"];
    }

    //类型（1：谈婚，2：论嫁，3：问答）必传
    [dic setValue:@"1" forKey:@"type"];
    //层级（1,2,3）必传
    [dic setValue:@"2" forKey:@"replySource"];
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"replyUserId"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_CommonEva];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                
                NSString *isZan = [data valueForKey:@"data"];
                if ([isZan isKindOfClass:[NSString class]]) {
                    
                    model.isZan = isZan;
                    if (isZan.length > 0) {
                        model.likes++;
                    } else {
                        model.likes--;
                    }
                    
                    [weakSelf.tableview reloadData];
                }
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {

    }];
}

@end
